﻿using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastServer
{
    /// <summary>
    /// WebApplication 拓展
    /// </summary>
    public static class AppWebApplicationBuilderExtensions
    {
        /// <summary>
        /// Web 应用注入
        /// </summary>
        /// <param name="webApplicationBuilder">Web应用构建器</param>
        /// <param name="configure"></param>
        /// <returns>WebApplicationBuilder</returns>
        public static WebApplicationBuilder Inject(this WebApplicationBuilder webApplicationBuilder, Action<WebApplicationBuilder, InjectOptions> configure = default)
        {
            // 载入服务配置选项
            var configureOptions = new InjectOptions();
            configure?.Invoke(webApplicationBuilder, configureOptions);

            // 为了兼容 .NET 5 无缝升级至 .NET 6，故传递 WebHost 和 Host
            InternalApp.WebHostEnvironment = webApplicationBuilder.Environment;

            // 初始化配置
            InternalApp.ConfigureApplication(webApplicationBuilder.WebHost, webApplicationBuilder.Host);

            return webApplicationBuilder;
        }

        /// <summary>
        /// 解决 .NET6 WebApplication 模式下二级虚拟目录错误问题
        /// </summary>
        /// <param name="app"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseVirtualPath(this WebApplication app, Action<IApplicationBuilder> configuration)
        {
            if (!string.IsNullOrWhiteSpace(App.Settings?.VirtualPath))
            {
                return app.Map(App.Settings.VirtualPath, configuration);
            }

            configuration(app);
            return app;
        }
    }
}
